package com.zking.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.zking.dao.domain.SysUser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class RequestUtils {

    //private static Logger logger = LoggerFactory.getLogger(RequestUtils.class);

    /**
     * 	获取当前登录的用户，若用户未登录，则返回未登录 json
     * @return
     */
    public static SysUser currentLoginUser() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Object principal = subject.getPrincipals().getPrimaryPrincipal();
            if (principal instanceof SysUser) {
                return (SysUser) principal;
            }
        }
        return null;
    }

    /**
     * 根据是否打包成jar，来获取类的信息
     * @param packageName 控制器所在的包路径
     * @return 控制器下所有.class文件
     */
    public List<String> getAllClass (String packageName) throws IOException {
        List<String> classNames = new ArrayList<>();
        String path = this.getClass().getResource("/").getPath();
        path = URLDecoder.decode(path, "UTF-8");
        if (path.lastIndexOf(".jar") != -1) {
            //如果是jar包，路径会有所不同
            path = path.substring(path.indexOf("file:/")+6, path.lastIndexOf(".jar")+4);
            //System.out.println("path="+path);
            //读取压缩文件
            ZipInputStream zip = new ZipInputStream(new FileInputStream(path));
            for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
                //com\zking\web
                if (entry.getName().contains("Controller") && !entry.isDirectory()
                        && entry.getName().endsWith(".class")) {
                    String className = entry.getName();
                    classNames.add(className.substring(className.lastIndexOf("/")+1));
                }
            }
        } else {
            //不是jar环境，正常路径
            path += packageName;
            classNames= Arrays.asList(new File(path).list());
        }
        return classNames;
    }



}
